package panda.android.notebook;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import panda.android.notebook.File.FileUtils;
import panda.android.notebook.Utils.Utils;
import panda.android.notebook.dialog.KBDDialog;
import panda.android.notebook.dialog.KBDDialog.Insert;
import panda.android.notebook.dialog.LuyinDialog;
import panda.android.notebook.popupWin.PopupWin;
import panda.android.notebook.popupWin.PopupWin.ItemClick;
import panda.android.notebook.popupWin.SignPopWin;
import panda.android.notebook.popupWin.SignPopWin.SignClick;
import panda.android.notebook.view.ColorSelectDialog;
import panda.android.notebook.view.ColorSelectDialog.OnColorChangedListener;
import panda.android.notebook.view.ImageEditView;
import panda.android.notebook.view.Tuya;
import panda.android.notebook.view.Word;
import panda.android.notebook.view.WordModel;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements Tuya.WordInterface {

	public static int SCREEN_WIDTH;
	public static int SCREEN_HEIGHT;
	private static final int RESULT_LOAD_IMAGE = 0;
	private static final int RESULT_CAMERA = 1;
	private static final int RESULT_VIDEO = 2;

	Tuya tuya;
	ImageEditView editView;
	String openFileName = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		SCREEN_WIDTH = dm.widthPixels;
		SCREEN_HEIGHT = dm.heightPixels;

		setContentView(R.layout.activity_main);

		tuya = (Tuya) findViewById(R.id.tuya);
		tuya.setWordInterface(this);

		editView = (ImageEditView) findViewById(R.id.imgeditview);

		((ImageButton) findViewById(R.id.btn_space))
				.setOnClickListener(clickListener);
		((ImageButton) findViewById(R.id.btn_enter))
				.setOnClickListener(clickListener);
		((ImageButton) findViewById(R.id.btn_delete))
				.setOnClickListener(clickListener);

		((TextView) findViewById(R.id.btn_fuhao))
				.setOnClickListener(clickListener);

		((TextView) findViewById(R.id.btn_file))
				.setOnClickListener(clickListener);

		((ImageButton) findViewById(R.id.btn_width))
				.setOnClickListener(clickListener);
		((ImageButton) findViewById(R.id.btn_color))
				.setOnClickListener(clickListener);
		((ImageButton) findViewById(R.id.btn_openTy))
				.setOnClickListener(clickListener);
		((ImageButton) findViewById(R.id.btn_openkbd))
				.setOnClickListener(clickListener);

		((ImageButton) findViewById(R.id.btn_camera))
				.setOnClickListener(clickListener);

		((ImageButton) findViewById(R.id.btn_luyin))
				.setOnClickListener(clickListener);
		((ImageButton) findViewById(R.id.btn_video))
				.setOnClickListener(clickListener);

		tuya.initLayout(this);

		Utils utils = new Utils();
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				utils.width(40), utils.height(40));
		params.setMargins(10, 5, 10, 5);
		((ImageView) findViewById(R.id.icon)).setLayoutParams(params);

		((TextView) findViewById(R.id.title)).setText("手写笔记");
		((TextView) findViewById(R.id.title)).setTextSize(utils.fontsize(12));

		initPop();
	}

	PopupWin filePop;
	PopupWin cameraPop;
	KBDDialog kbdDialog;
	SignPopWin signPopWin;

	private void initPop() {
		signPopWin = new SignPopWin(MainActivity.this);
		signPopWin.setSignClick(new SignClick() {

			@Override
			public void signclick(String tag) {
				// TODO Auto-generated method stub
				editView.addSign(tag);
			}
		});

		kbdDialog = new KBDDialog(MainActivity.this, R.style.dialog);
		kbdDialog.setInsert(new Insert() {

			@Override
			public void inertString(String string) {
				// TODO Auto-generated method stub
				char[] c = string.toCharArray();
				for (int i = 0; i < c.length; i++) {
					editView.addSign(String.valueOf(c[i]));
				}
			}
		});
		{
			final String[] strings = { "新建", "打开", "保存" };
			filePop = new PopupWin(MainActivity.this, strings);
			filePop.setItemClick(new ItemClick() {

				@Override
				public void itemclick(String tag) {
					// TODO Auto-generated method stub
					if (tag.equals(strings[0])) {
						editView.clean();
					}
					if (tag.equals(strings[1])) {
						new AlertDialog.Builder(MainActivity.this)
								.setTitle("请选择文件")
								.setItems(getFileNames(),
										new fileClickListener()).show();
					}
					if (tag.equals(strings[2])) {
						EditText et = new EditText(MainActivity.this);
						et.setText(openFileName);
						new AlertDialog.Builder(MainActivity.this)
								.setView(et)
								.setTitle("请输入文件名")
								.setPositiveButton("确定",
										new saveFileClickListener(et)).show();
					}
				}
			});
		}

		{
			final String[] strings = { "相机", "图库" };
			cameraPop = new PopupWin(MainActivity.this, strings);
			cameraPop.setItemClick(new ItemClick() {

				@Override
				public void itemclick(String tag) {
					// TODO Auto-generated method stub
					if (tag.equals(strings[0])) {
						Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						filename = System.currentTimeMillis() + ".jpg";
						if (isHasSdcard()) {
							File file = new File(SDCARD_ROOT_PATH
									+ SAVE_PATH_IN_SDCARD);
							file.mkdirs();
							i.putExtra(MediaStore.EXTRA_OUTPUT,
									Uri.fromFile(new File(file, filename)));
						}
						startActivityForResult(i, RESULT_CAMERA);
					}
					if (tag.equals(strings[1])) {
						Intent i = new Intent(
								Intent.ACTION_PICK,
								android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						startActivityForResult(i, RESULT_LOAD_IMAGE);
					}
				}
			});
		}

	}

	OnClickListener clickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_space:
				editView.Space();
				break;
			case R.id.btn_enter:
				editView.Enter();
				break;
			case R.id.btn_delete:
				editView.delText();
				break;
			case R.id.btn_fuhao:
				signPopWin.show(v);
				break;

			case R.id.btn_width:
				showWidthPop(v);
				break;
			case R.id.btn_color:
				showColorPop();
				break;
			case R.id.btn_openTy:
				tuya.setShow(!tuya.isShow());
				v.setBackgroundResource(tuya.isShow() ? R.drawable.button_blue
						: R.drawable.button_white);

				if (kbdDialog.isShow())
					kbdDialog.dismiss();
				break;
			case R.id.btn_openkbd:
				if (tuya.isShow()) {
					tuya.setShow(false);
					((ImageButton) findViewById(R.id.btn_openTy))
							.setBackgroundResource(R.drawable.button_white);
				}

				if (kbdDialog.isShow()) {
					kbdDialog.dismiss();
				} else {
					kbdDialog.show();
				}
				break;
			case R.id.btn_file:
				filePop.show(v);
				break;

			case R.id.btn_camera:
				cameraPop.show(v);
				break;
			case R.id.btn_luyin:
				LuyinDialog dialog = new LuyinDialog(MainActivity.this,
						R.style.dialog);
				dialog.setP(new panda.android.notebook.dialog.LuyinDialog.sendPath() {

					@Override
					public void Path(String path) {
						// TODO Auto-generated method stub
						WordModel resources = new WordModel(MainActivity.this,
								WordModel.LUYIN);
						resources.setPath(path);
						editView.addResource(resources);
					}
				});
				dialog.show();
				break;

			case R.id.btn_video:
				Intent i = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
				filename = System.currentTimeMillis() + ".3pg";
				if (isHasSdcard()) {
					File file = new File(SDCARD_ROOT_PATH + "/note/video");
					file.mkdirs();
					i.putExtra(MediaStore.EXTRA_OUTPUT,
							Uri.fromFile(new File(file, filename)));
				}
				startActivityForResult(i, RESULT_VIDEO);
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();

			WordModel resources = new WordModel(this, WordModel.PIC);
			resources.setPath(picturePath);
			editView.addResource(resources);
		}

		if (requestCode == RESULT_CAMERA && resultCode == RESULT_OK) {

			WordModel resources = new WordModel(this, WordModel.PIC);
			resources
					.setPath(SDCARD_ROOT_PATH + SAVE_PATH_IN_SDCARD + filename);
			editView.addResource(resources);
		}

		if (requestCode == RESULT_VIDEO && resultCode == RESULT_OK) {

			WordModel resources = new WordModel(this, WordModel.VIDEO);
			resources.setPath(SDCARD_ROOT_PATH + "/note/video/" + filename);
			editView.addResource(resources);
		}
	}

	public static final String SDCARD_ROOT_PATH = android.os.Environment
			.getExternalStorageDirectory().getAbsolutePath();// 路径
	public static final String SAVE_PATH_IN_SDCARD = "/note/img/"; // 图片及其他数据保存文件夹
	private String filename = "";

	public static boolean isHasSdcard() {
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	PopupWindow popupWindow;

	private void showWidthPop(View v) {
		String s[] = { "极细", "细", "正常", "粗", "特粗" };
		ListView listView = new ListView(this);
		listView.setOnItemClickListener(itemClickListener);
		listView.setBackgroundResource(R.drawable.abs__dialog_full_holo_light);
		listView.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.select_dialog_item, s));
		popupWindow = new PopupWindow(listView, 200, 300);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.showAsDropDown(v);
	}

	OnItemClickListener itemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			popupWindow.dismiss();
			editView.setWordWidth(arg2 + 1);
		}
	};

	int mColor = Color.RED;

	private void showColorPop() {
		new ColorSelectDialog(this, mColor, R.style.dialog,
				new OnColorChangedListener() {

					@Override
					public void colorChanged(int color) {
						// TODO Auto-generated method stub
						mColor = color;
						editView.setTextColor(color);
						tuya.setTextColor(color);
					}
				}).show();
	}

	public void sendWord(Word word) {
		editView.addText(word);
	};

	private String[] getFileNames() {
		List<String> item = new ArrayList<String>();

		File file = new File(Environment.getExternalStorageDirectory()
				+ "/note");
		String s[] = file.list();
		for (int i = 0; i < s.length; i++) {
			if (s[i].endsWith(".note")) {
				item.add(s[i]);
			}
		}
		String itemString[] = new String[item.size()];
		for (int i = 0; i < itemString.length; i++) {
			itemString[i] = item.get(i);
		}
		return itemString;
	}

	class saveFileClickListener implements AlertDialog.OnClickListener {
		EditText et;

		public saveFileClickListener(EditText et) {
			this.et = et;
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			if (!et.getText().toString().equals("")) {
				new FileUtils().SaveFile(editView.getBitmapMDs(), et.getText()
						.toString() + ".note");
				openFileName = et.getText().toString();
			} else
				Toast.makeText(MainActivity.this, "请输入文件名！", Toast.LENGTH_LONG)
						.show();
		}
	}

	class fileClickListener implements
			android.content.DialogInterface.OnClickListener {
		String itemString[];

		public fileClickListener() {
			this.itemString = getFileNames();
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			openFileName = itemString[which];
			List<WordModel> bitmapMDs = new FileUtils().openFile(openFileName,
					MainActivity.this);
			if (bitmapMDs == null)
				return;
			editView.setBitmapMDs(bitmapMDs);

			openFileName = itemString[which].replace(".note", "");
		}

	}
}
